package com.cy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.common.entity.Result;
import com.cy.pojo.Bike;
import com.cy.pojo.Rent;
import com.cy.pojo.vo.BikeTreeVo;
import com.cy.pojo.vo.SearchVo;
import com.cy.service.AdminService;
import com.cy.service.BikeService;
import com.cy.service.RentService;
import com.cy.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author 残影
 * @description 租赁表
 * @date 2022-04-30
 */
@RestController
@RequestMapping("/rent")
@Api(tags = "租赁表模块")
public class RentController {
    @Autowired
    private RentService rentService;
    @Autowired
    private BikeService bikeService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private AdminService adminService;

    @GetMapping("/statistics")
    @ApiOperation("statistics")
    public Result statistics() {
        // 车辆总数
        Integer allBikeCount = 0;
        // 在库车辆
        Integer bikeBikeStock = 0;
        List<Bike> bikeList = bikeService.list(null);
        allBikeCount = bikeList.size();
        for (Bike bike : bikeList) {
            if (bike.getStatus() == 0) {
                bikeBikeStock++;
            }
        }
        // 学生总数
        Integer studentCount = studentService.count(null);

        //管理员总数
        Integer adminCount = adminService.count(null);

        // 租赁总数
        Integer rentCount = 0;
        Integer rentAmountCount = 0;
        Integer rentAntecedentCount = 0;
        List<Rent> rentList = rentService.list(null);
        rentCount = rentList.size();
        for (Rent rent : rentList) {
            if (StringUtils.isNotEmpty(rent.getRentAmount())) {
                rentAmountCount += Integer.parseInt(rent.getRentAmount());
            }
            if (rent.getReturnType() == 0 && StringUtils.isNotEmpty(rent.getAntecedentMoney())) {
                rentAntecedentCount += Integer.parseInt(rent.getAntecedentMoney());
            }
        }

        Map<String, Integer> map = new LinkedHashMap<>();
        map.put("allBikeCount", allBikeCount);
        map.put("bikeBikeStock", bikeBikeStock);
        map.put("studentCount", studentCount);
        map.put("adminCount", adminCount);
        map.put("rentCount", rentCount);
        map.put("rentAmountCount", rentAmountCount);
        map.put("rentAntecedentCount", rentAntecedentCount);

        return Result.ok("查询成功", map);
    }

    /**
     * 根据ID查询租赁表
     */
    @GetMapping("{id}")
    @ApiOperation("根据ID查询租赁表")
    public Result findById(@PathVariable Integer id) {
        Rent rent = rentService.getById(id);
        if (rent != null) {
            return Result.ok("查询租赁表成功", rent);
        } else {
            return Result.failed(201, "没有该租赁表");
        }
    }

    /**
     * 分页查询租赁表
     */
    @ApiOperation("分页查询租赁表")
    @GetMapping("/list")
    public Result list(SearchVo searchVo) {
        //分页构造器
        Page<Rent> buildPage = new Page<>(searchVo.getPage(), searchVo.getLimit());
        //条件构造器
        QueryWrapper<Rent> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(searchVo.getName())) {
            queryWrapper.like("student_name", searchVo.getName());
        }
        Date startTime = searchVo.getStartTime();
        Date endTime = searchVo.getEndTime();
        if (ObjectUtils.isNotEmpty(startTime) && ObjectUtils.isNotEmpty(endTime)) {
            queryWrapper.between("rent_time", startTime, endTime);
        }
        IPage<Rent> pageList = rentService.page(buildPage, queryWrapper);
        return Result.ok("查询成功", pageList.getRecords()).put("total", pageList.getTotal());
    }

    @ApiOperation("查询自行车树")
    @GetMapping("rentTree")
    public Result rentTree() {
        List<Bike> bikeList = bikeService.list(null);
        Set<BikeTreeVo> bikeTreeVoSet = new HashSet<>();
        for (Bike bike : bikeList) {
            BikeTreeVo bikeTreeVo = new BikeTreeVo();
            bikeTreeVo.setLabel(bike.getBikeType());
            bikeTreeVo.setValue(bike.getBikeType());
            bikeTreeVoSet.add(bikeTreeVo);
        }
        for (BikeTreeVo bikeTreeVo : bikeTreeVoSet) {
            List<BikeTreeVo> list = new ArrayList<>();
            for (Bike bike : bikeList) {
                if (bikeTreeVo.getLabel().equals(bike.getBikeType())) {
                    BikeTreeVo bikeTreeVo1 = new BikeTreeVo();
                    bikeTreeVo1.setLabel(bike.getBikeNumber());
                    bikeTreeVo1.setValue(bike.getBikeNumber());
                    list.add(bikeTreeVo1);
                }
            }
            bikeTreeVo.setChildren(list);
        }
        return Result.ok("查询成功", bikeTreeVoSet);
    }

    /**
     * 保存租赁表
     */
    @PostMapping
    @ApiOperation("保存租赁表")
    public Result save(@RequestBody Rent rent) {
        QueryWrapper<Bike> wrapper = new QueryWrapper<>();
        wrapper.eq("bike_type", rent.getBikeType())
                .eq("bike_number", rent.getBikeNumber());
        Bike bike = bikeService.getOne(wrapper);
        if (bike.getStatus() == 1) {
            return Result.failed("该自行车已经被租赁");
        }
        bike.setStatus(1);
        bikeService.updateById(bike);

        rent.setRentTime(new Date());
        boolean b = rentService.saveOrUpdate(rent);
        if (b) {
            return Result.ok("保存用户租赁表成功", rent);
        } else {
            return Result.failed("保存租赁表失败");
        }
    }

    /**
     * 修改租赁表
     */
    @PutMapping
    @ApiOperation("修改租赁表")
    public Result update(@RequestBody Rent rent) {
        boolean b = rentService.saveOrUpdate(rent);
        if (b) {
            return Result.ok("修改租赁表成功", rent);
        } else {
            return Result.failed("修改租赁表失败");
        }
    }

    @PutMapping("returnBike")
    @ApiOperation("归还单车")
    public Result returnBike(@RequestBody Rent rent) {
        QueryWrapper<Bike> wrapper = new QueryWrapper<>();
        wrapper.eq("bike_type", rent.getBikeType())
                .eq("bike_number", rent.getBikeNumber());
        Bike bike = bikeService.getOne(wrapper);
        bike.setStatus(0);
        bikeService.updateById(bike);

        Rent rent1 = rentService.getById(rent.getId());
        if (rent1 == null) {
            return Result.failed("租赁信息不存在");
        }
        if (rent1.getReturnType() == 1) {
            return Result.failed("单车已归还");
        }
        rent.setReturnTime(new Date());
        rent.setReturnType(1);
        boolean b = rentService.saveOrUpdate(rent);
        if (b) {
            return Result.ok("归还成功", rent);
        } else {
            return Result.failed("归还失败");
        }
    }

    /**
     * 删除租赁表
     */
    @DeleteMapping("{id}")
    @ApiOperation("删除租赁表")
    public Result delete(@PathVariable Long id) {
        boolean b = rentService.removeById(id);
        if (b) {
            return Result.ok("删除租赁表成功");
        } else {
            return Result.failed("删除租赁表失败");
        }
    }
}
